<template>
	<view class="container">
		<TopBtn v-if="type == 1" :title="'我的会诊'"></TopBtn>
		<TopBtn v-if="type == 2" :title="'今日会诊'"></TopBtn>
		<view class="nav" v-if="type == 1">
			<view :class="{ act: request.status == n.id }" v-for="n in navList" :key="n.id" @click="changeNav(n.id)">
				{{ n.name }}
			</view>
		</view>
		<view :class="type == 1 ? 'info pt_100' : 'info'">
			<view class="currency_card" v-for="(n, i) in list" :key="n.id" @click="
          goInfo('pages/ConsultationRoom/consultationDetails/consultationDetails', n.consultationId)
        ">
				<view class="currency_info">
					<view class="Card_row alignItems">
						<view class="title">会诊目的：</view>
						<view class="text">
							{{ n.invitationPurpose }}
						</view>
					</view>
					<view class="Card_row">
						<view class="title">会诊时间：</view>
						<view class="text flex-center">
							<uni-dateformat :date="n.invitationTime" format="yyyy-MM-dd hh:mm"></uni-dateformat>
							<view class="xdtime" v-if="n.flag">
								{{ n.flag }}
							</view>
						</view>
					</view>
					<view class="Card_row alignItems">
						<view class="title">问诊医生：</view>
						<view class="text">
							<doctorCard :data="n"></doctorCard>
						</view>
					</view>
					<view class="xian" v-if="n.status == 4"></view>
					<view class="Card_row">
						<view class="time mt_30 flex-sp-center">
							<uni-dateformat :date="n.createTime" format="yyyy-MM-dd hh:mm"></uni-dateformat>
							<!-- 聊天入口 -->
							<view class="kqhz flex-center-center"
								v-if="n.invitationTime < new Date() && userId == n.doctorId &&( n.status == 3 || n.status == 4)  && !n.groupId"
								@click.stop="openConsultationInfo(n,n.consultationId)">
								开启会诊
							</view>
							<view class="kqhz flex-center-center" v-else-if="n.groupId && n.status == 4"
								@click.stop="openConsultationInfo(n)">
								去沟通
							</view>
							<view class="flex-center" v-else>
								查看详情
								<uni-icons type="right" size="16" color="#999"></uni-icons>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="add" @click="goInfo('pages/ConsultationRoom/addConsultation/addConsultation')">
			发布
		</view>
	</view>
</template>

<script>
	import {
		addHoursToTimestamp
	} from '@/utils/time'
	import {
		CreateGroup,
		SwitchConversation,
		UpdateGroupProfile,
		SendGroupMessage
	} from '@/utils/TIM'
	import {
		updateConsultationInfo
	} from '@/api/Consultation'
	import {
		getMyConsultationInfoPage,
		getTodayConsultationInfoPage,
		openConsultationInfo
	} from '@/api/ConsultationRoom'
	export default {
		data() {
			return {
				data: {},
				userId: uni.getStorageSync('userId'),
				navList: [{
						id: 1,
						name: '待缴费',
					},
					{
						id: 2,
						name: '待接诊',
					},
					{
						id: 3,
						name: '待会诊',
					},
					{
						id: 4,
						name: '会诊中',
					},
					{
						id: 5,
						name: '已结束',
					},
				],
				id: '',
				list: [],
				request: {
					pageNo: 1,
					pageSize: 10,
					status: 1,
				},
				maxNum: '',
				type: 1,
			}
		},

		onLoad(options) {
			if (options.type) {
				this.type = options.type
			}
			this.getMyConsultationInfoPage()
		},
		onReachBottom() {
			if (this.maxNum <= this.request.pageNo) return
			this.request.pageNo = this.request.pageNo + 1
			this.getMyConsultationInfoPage()
		},
		methods: {
			changeNav(e) {
				this.request.status = e
				this.request.pageNo = 1
				this.list = []
				this.getMyConsultationInfoPage()
			},
			getMyConsultationInfoPage() {
				if (this.type == 1) {
					getMyConsultationInfoPage(this.request).then(res => {
						this.list.push(...res.data.list)
						let num = res.data.total / this.request.pageSize
						if (num.toString().includes('.')) {
							num = Math.ceil(num)
						}
						this.maxNum = num
					})
				}
				if (this.type == 2) {
					this.request.status = null
					getTodayConsultationInfoPage(this.request).then(res => {
						this.list.push(...res.data.list)
						let num = res.data.total / this.request.pageSize
						if (num.toString().includes('.')) {
							num = Math.ceil(num)
						}
						this.maxNum = num
					})
				}
			},
			goInfo(e, id) {
				if (id) {
					uni.navigateTo({
						url: `/${e}?id=${id}`,
					})
				} else {
					uni.navigateTo({
						url: `/${e}`,
					})
				}
			},
			// 创建会话
			async handleCreateConversation(e, memberList = []) {
				if (!e.openId) {
					uni.showToast({
						title: '患者 openId 不能为空',
						duration: 2000,
						icon: 'none',
					})
					return
				}
				// 患者信息
				const patient = {
					userID: e.openId,
					userName: e.patientName,
				}

				console.log('-- GroupMemberList ---------------', e)
				console.log('-- GroupMemberList ---------------', [patient, ...memberList])

				// 创建群组
				const newGroup = await CreateGroup(
					[patient, ...memberList],
					'会诊',
					`${e.patientName}(患者)的会诊`
				)

				// 获取 群组ID
				const {
					groupID
				} = newGroup.data.group

				// 发送群系统消息
				const message = {
					businessID: 'tip',
					type: 'highlight', // default | highlight | card | topbar |
					text: '会诊已开启，请及时进行沟通',
				}
				SendGroupMessage(groupID, message)

				// 计算群组会话结束时间
				const startTime = Date.now()
				const endTime = addHoursToTimestamp(startTime, 48)

				// 组织会话信息
				const consultationInfo = {
					id: e.id,
					consultationMethod: e.consultationMethod,
					departName: e.departName,
					hospitalName: e.hospitalName,
					doctorId: e.doctorId,
					doctorName: e.doctorName,
					patientId: e.patientId,
					patientName: e.patientName,
					groupId: e.groupId,
					status: e.status,
					otherDoctors: e.consultationRoomRespVOS.map(item => {
						return {
							userID: item.participants,
							userName: item.participantsName,
						}
					}),
				}

				try {
					// 更新群组信息：会话结束时间
					await UpdateGroupProfile(groupID, {
						avatar: 'https://img.tukuppt.com/png_preview/00/34/18/K4TDENStvR.jpg!/fw/780',
						groupCustomField: [{
								key: 'endTime',
								value: String(endTime),
							},
							{
								key: 'consultation',
								value: JSON.stringify(consultationInfo),
							},
						],
					})
				} catch (error) {
					console.log('-- UpdateGroupProfile ---------------', error)
				}

				try {
					// 会诊信息中增加 groupID
					await updateConsultationInfo({
						id: e.consultationId,
						groupId: groupID, // 群组ID
						receiveTime: startTime, // 接诊时间
					})
				} catch (error) {
					console.log('-- updateConsultationInfo ---------------', error)
				}
			},
			openConsultationInfo(e, id) {
				// 手动开启会诊
				var that = this
				if (id) {
					uni.showLoading({
						title: '加载中',
						mask: true
					});
					openConsultationInfo({
						consultationId: id
					}).then(res => {
						uni.hideLoading();
						uni.showToast({
							title: '开启成功',
							duration: 1000,
							icon: "none",
							mask: true
						});
						setTimeout(function() {
							that.start(e)
						}, 1000);
					})
				} else {
					this.start(e)
				}
			},
			start(e) {
				console.log('>>>> start >>>>>>>>>>>>>>>>>>>>>', e)
				if (e.groupId) {
					const conversationID = `GROUP${e.groupId}`
					SwitchConversation(conversationID)
				} else {
					// 创建会话
					const memberList = e.consultationRoomRespVOS.map(item => {
						return {
							userID: String(item.doctorId),
							userName: item.doctorName,
						}
					})

					this.handleCreateConversation(e, memberList)
				}
			},
		},
	}
</script>

<style lang="less">
	.add {
		width: 127rpx;
		height: 127rpx;
		background: #3e6efe;
		border-radius: 50%;
		background-image: url(@/static/ConsultationRoom/add2.png);
		background-size: 100% 100%;
		position: fixed;
		right: 30rpx;
		bottom: 184rpx;
		text-align: center;
		font-weight: 500;
		font-size: 22rpx;
		color: #ffffff;
		padding-top: 80rpx;
		box-sizing: border-box;
	}

	.xian {
		width: 649rpx;
		height: 1rpx;
		background-color: #eeeeee;
	}

	.kqhz {
		width: 195rpx;
		height: 70rpx;
		background: #3e6efe;
		border-radius: 9rpx;
		font-weight: 500;
		font-size: 26rpx;
		color: #ffffff;
	}

	.xdtime {
		font-weight: 500;
		font-size: 22rpx;
		color: #3e6efe;
		padding: 6rpx 15rpx;
		border-radius: 10rpx;
		border: 1px solid #3e6efe;
		margin-left: 15rpx;
	}

	.nav {
		display: flex;
		align-items: center;
		height: 80rpx;
		justify-content: space-between;
		width: 100%;
		position: fixed;
		z-index: 99;
		top: 128rpx;

		&>view {
			flex: 1;
			text-align: center;
		}

		background-color: #fff;
		font-weight: 500;
		font-size: 32rpx;
		color: #999999;

		.act {
			font-weight: bold;
			color: #333333;
		}
	}

	.info {
		padding: 30rpx 30rpx;

		.currency_card {
			position: relative;

			.state {
				position: absolute;
				right: 0;
				top: 0;
				padding: 0 5rpx;
				min-width: 100rpx;
				height: 50rpx;
				background: #f9fbfe;
				font-size: 28rpx;
				color: #3e6efe;
				text-align: center;
				line-height: 50rpx;
				border-radius: 0 21rpx;
			}
		}

		&>view {
			margin-bottom: 27rpx;
		}

		.currency_info {
			margin-top: 21rpx;

			&:last-child {
				margin-top: 0rpx;
			}

			.Card_row {
				display: flex;
				font-weight: 500;
				font-size: 28rpx;
				color: #333;
				align-items: center;
				margin-bottom: 20rpx;

				.title {
					width: 150rpx;
					color: #999;
				}

				.time {
					flex: 1;
					color: #999;
				}

				.text {
					flex: 1;
				}
			}

			.alignItems {
				align-items: self-start;
			}
		}
	}

	.pt_100 {
		padding-top: 100rpx;
	}
</style>